package com.itheima.interceptor;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //        获取请求url
        String url = request.getRequestURI();
//        登录不拦截
        if (url.contains("login")) {
            return true;
        } else {
//            非登录 获取请求头token
            String jwt = request.getHeader("token");
//            为空拦截
            if (jwt == null || jwt.isEmpty()) {
                response.setStatus(HttpStatus.SC_UNAUTHORIZED);
                return false;
            }
//            不为空则解析
            try {
                Claims claims = JwtUtils.parseJWT(jwt);
                Integer empId = Integer.valueOf(claims.get("id").toString());
                CurrentHolder.setCurrentId(empId);
            } catch (Exception e) {
                e.printStackTrace();
                log.info("解析令牌失败, 返回错误结果");
                response.setStatus(HttpStatus.SC_UNAUTHORIZED);
                return false;
            }

            return true;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentHolder.remove();
    }
}
